﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using DAL;
using MediatR;
using Microsoft.Data.SqlClient;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.Read.Apilaction.CommandHandler.StoreCommandHandler
{
    /// <summary>
    /// 入库产品显示
    /// </summary>
    public class StoreproductCommandHandler : IRequestHandler<StoreproductCommand, ApiReqult<ApIPageing<StoreproductDTO>>>
    {
        private readonly DBHelper bHelper;
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public StoreproductCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }

        /// <summary>
        /// 入库产品显示
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<ApIPageing<StoreproductDTO>>> Handle(StoreproductCommand request, CancellationToken cancellationToken)
        {
            ApiReqult<ApIPageing<StoreproductDTO>> result = new ApiReqult<ApIPageing<StoreproductDTO>>();
            try
            {
                int skip = (request.PageIdex - 1) * request.PageSize;
                int take = request.PageSize;

                // 构建查询条件（单表查询）
                string whereClause = "WHERE Pid = 0 AND IsDelete = 0";
                if (request.ProductId.HasValue)
                {
                    whereClause += $" AND ProId = {request.ProductId.Value}"; // 假设ManagementModels的产品ID字段为ProId
                }
                else if (!string.IsNullOrEmpty(request.ProductName))
                {
                    whereClause += $" AND ProductName LIKE '%{request.ProductName}%'"; // 假设ManagementModels包含产品名称字段
                }

                // 构建查询总数的 SQL 语句（单表）
                string countSql = $"SELECT COUNT(*) FROM ManagementModels {whereClause};";

                // 获取总数
                int totalCount = Convert.ToInt32(bHelper.Scalar(countSql));

                // 构建分页查询的 SQL 语句（单表）
                string sql = $"SELECT * FROM ManagementModels {whereClause} ORDER BY ProId OFFSET {skip} ROWS FETCH NEXT {take} ROWS ONLY;";

                List<StoreproductDTO>? managementModels = bHelper.GetList<StoreproductDTO>(sql);

                if (managementModels != null)
                {
                    ApIPageing<StoreproductDTO> pageData = new ApIPageing<StoreproductDTO>();
                    pageData.TotalCount = totalCount;
                    pageData.TotalPage = (int)Math.Ceiling(pageData.TotalCount * 1.0 / request.PageSize);
                    pageData.List = managementModels;
                    result.Data = pageData;
                    result.Msg = ApiEnum.查询成功.ToString();
                }
                else
                {
                    result.Msg = ApiEnum.查询失败.ToString();
                    result.Code = ApiEnum.查询失败;
                }

            }
            catch (SqlException ex)
            {
                logger.Error(ex.Message, "执行 SQL 查询时发生异常");
                result.Msg = ApiEnum.查询失败.ToString();
                result.Code = ApiEnum.查询失败;
            }
            return await Task.FromResult(result);
        }
    }
}